<template>
  <div class="contract-progress-detail">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>合同进度详情</h2>
        <button @click="goBack" class="btn btn-secondary">
          <i class="fa fa-arrow-left mr-2"></i>返回上一级
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载合同中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <div class="alert alert-danger">
        <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
      </div>
    </div>

    <div v-if="contract && !loading" class="card mt-4">
      <div class="card-body">
        <!-- 合同详情 - 上半部分 -->
        <h3 class="contract-name">{{ contract.name }}</h3>
        <div class="contract-info">
          <p><strong>合同ID:</strong> {{ contract.id }}</p>
          <p><strong>客户:</strong> {{ contract.customer?.companyName || '未指定' }}</p>
          <p><strong>项目经理:</strong> {{ contract.projectManager?.name || '未指定' }}</p>
          <p><strong>合同状态:</strong> {{ getProgressText(milestoneStatus) }}</p>
          <p><strong>创建时间:</strong> {{ formatDate(contract.createTime) }}</p>
          <p><strong>更新时间:</strong> {{ formatDate(contract.updateTime) }}</p>
        </div>

        <!-- 进度条 -->
        <div class="progress-section mt-4">
          <h4>合同进度</h4>
          <div class="progress">
            <div
                :class="['progress-bar', getProgressClass(milestoneStatus)]"
                :style="{ width: getProgressWidth(milestoneStatus) }"
            >
              {{ getProgressText(milestoneStatus) }} ({{ milestoneStatus * 25 }}%)
            </div>
          </div>
          <div class="progress-steps mt-3">
            <div class="step" :class="{ active: milestoneStatus >= 1 }">
              <div class="step-indicator">1</div>
              <div class="step-text">未开始</div>
            </div>
            <div class="progress-line" :class="{ active: milestoneStatus >= 2 }"></div>
            <div class="step" :class="{ active: milestoneStatus >= 2 }">
              <div class="step-indicator">2</div>
              <div class="step-text">定金阶段</div>
            </div>
            <div class="progress-line" :class="{ active: milestoneStatus >= 3 }"></div>
            <div class="step" :class="{ active: milestoneStatus >= 3 }">
              <div class="step-indicator">3</div>
              <div class="step-text">执行阶段</div>
            </div>
            <div class="progress-line" :class="{ active: milestoneStatus >= 4 }"></div>
            <div class="step" :class="{ active: milestoneStatus >= 4 }">
              <div class="step-indicator">4</div>
              <div class="step-text">已完成</div>
            </div>
          </div>
        </div>

        <!-- 合同条款 -->
        <div class="clauses-section mt-4">
          <h4>合同条款</h4>
          <div v-if="clauses.length > 0" class="clauses-list">
            <ul class="list-group">
              <li
                  v-for="clause in clauses"
                  :key="clause.id"
                  class="list-group-item"
              >
                <p class="mb-1"><strong>内容:</strong> {{ clause.content }}</p>
              </li>
            </ul>
          </div>
          <div v-else class="empty-message text-center py-2">
            <i class="fa fa-info-circle text-muted mr-2"></i>暂无条款
          </div>
        </div>
      </div>
    </div>

    <!-- 操作区域 - 下半部分 -->
    <div class="action-area mt-6">
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-gradient-primary text-white">
          <h4 class="mb-0">合同操作</h4>
        </div>
        <!-- 操作结果提示 -->
        <div v-if="operationSuccess" class="success-notification mt-6">
          <div class="notification-icon">
            <i class="fa fa-check-circle"></i>
          </div>
          <div class="notification-content">
            <h5 class="notification-title">操作成功</h5>
            <p class="notification-message">{{ operationMessage }}</p>
          </div>
        </div>
        <div class="card-body p-5">
          <!-- 不同进度的操作按钮 -->
          <div v-if="milestoneStatus === 1" class="action-buttons text-center">
            <button
                @click="startContractExecution"
                class="btn btn-lg btn-gradient-primary shadow lift transition-all duration-300"
                :disabled="loading"
            >
              <i class="fa fa-play mr-3"></i>开始履行合同
              <span class="badge bg-white text-primary ml-2">未开始</span>
            </button>
          </div>

          <div v-if="milestoneStatus === 2" class="action-buttons">
            <div class="form-floating mb-5">
              <textarea
                  id="depositDesc"
                  v-model="depositDescription"
                  class="form-control bg-light border-0 rounded-lg shadow-sm textarea-large"
                  rows="5"
                  disabled
              ></textarea>
              <label for="depositDesc">定金阶段描述</label>
            </div>
            <button
                @click="openDepositModal"
                class="btn btn-lg btn-gradient-info w-100 shadow lift transition-all duration-300"
                :disabled="loading"
            >
              <i class="fa fa-edit mr-3"></i>更新定金阶段
              <span class="badge bg-white text-info ml-2">进行中</span>
            </button>
          </div>

          <div v-if="milestoneStatus === 3" class="action-buttons">
            <div class="form-floating mb-5">
              <textarea
                  id="executionDesc"
                  v-model="executionDescription"
                  class="form-control bg-light border-0 rounded-lg shadow-xl textarea-large"
                  rows="5"
                  disabled
              ></textarea>
              <label for="executionDesc">执行阶段描述</label>
            </div>
            <button
                @click="openExecutionModal"
                class="btn btn-lg btn-gradient-primary w-100 shadow lift transition-all duration-300"
                :disabled="loading"
            >
              <i class="fa fa-cogs mr-3"></i>更新执行进度
              <span class="badge bg-white text-primary ml-2">进行中</span>
            </button>
          </div>

          <div v-if="milestoneStatus === 4" class="action-buttons text-center">
            <button
                @click="confirmArchiving"
                class="btn btn-lg btn-gradient-success shadow lift transition-all duration-300"
                :disabled="loading"
            >
              <i class="fa fa-archive mr-3"></i>确认归档合同
              <span class="badge bg-white text-success ml-2">已完成</span>
            </button>
          </div>

<!--          &lt;!&ndash; 操作结果提示 &ndash;&gt;-->
<!--          <div v-if="operationSuccess" class="success-notification mt-6">-->
<!--            <div class="notification-icon">-->
<!--              <i class="fa fa-check-circle"></i>-->
<!--            </div>-->
<!--            <div class="notification-content">-->
<!--              <h5 class="notification-title">操作成功</h5>-->
<!--              <p class="notification-message">{{ operationMessage }}</p>-->
<!--            </div>-->
<!--          </div>-->
        </div>
      </div>
    </div>

    <!-- 定金阶段模态框 -->
    <div v-show="depositModalVisible" class="modal" tabindex="-1" role="dialog" @click.self="depositModalVisible = false">
      <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">更新定金阶段描述</h5>
            <button @click="depositModalVisible = false" class="btn-close" type="button" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <textarea
                  v-model="depositModalContent"
                  class="form-control textarea-large"
                  rows="8"
                  placeholder="请输入定金阶段描述..."
              ></textarea>
            </div>
          </div>
          <div class="modal-footer">
            <button @click="depositModalVisible = false" class="btn btn-secondary" type="button">取消</button>
            <button @click="updateDepositDescription" class="btn btn-primary" type="button">保存修改</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 执行阶段模态框 -->
    <div v-show="executionModalVisible" class="modal" tabindex="-1" role="dialog" @click.self="executionModalVisible = false">
      <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">更新执行阶段描述</h5>
            <button @click="executionModalVisible = false" class="btn-close" type="button" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <textarea
                  v-model="executionModalContent"
                  class="form-control textarea-large"
                  rows="8"
                  placeholder="请输入执行阶段描述..."
              ></textarea>
            </div>
          </div>
          <div class="modal-footer">
            <button @click="executionModalVisible = false" class="btn btn-secondary" type="button">取消</button>
            <button @click="updateExecutionDescription" class="btn btn-primary" type="button">保存修改</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'ContractProgressDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()

    const contractId = ref(null)
    const contract = ref(null)
    const clauses = ref([])
    const milestoneStatus = ref(1)
    const depositDescription = ref('')
    const executionDescription = ref('')
    const loading = ref(true)
    const errorMessage = ref('')
    const operationSuccess = ref(false)
    const operationMessage = ref('')

    // 模态框状态
    const depositModalVisible = ref(false)
    const executionModalVisible = ref(false)
    const depositModalContent = ref('')
    const executionModalContent = ref('')

    // 进度状态映射
    const milestoneStatusMap = {
      1: "未开始",
      2: "定金阶段",
      3: "执行阶段",
      4: "已完成"
    }

    // 验证合同ID是否为有效数字
    const validateContractId = (id) => {
      if (!id) return false
      const numericId = Number(id)
      return !isNaN(numericId) && numericId > 0
    }

    // 获取合同详情
    const fetchContractDetails = () => {
      loading.value = true
      errorMessage.value = ''

      // 获取并验证合同ID
      const id = route.params.contractId
      console.log('当前路由参数 contractId:', id)

      if (!validateContractId(id)) {
        errorMessage.value = `无效的合同ID: ${id}`
        console.error(errorMessage.value)
        setTimeout(() => {
          router.push('/employee/ongoing-contracts')
        }, 2000)
        loading.value = false
        return
      }

      contractId.value = Number(id)
      console.log('验证后的合同ID:', contractId.value)

      axios.get(`/auth/contracts/${contractId.value}/progress`)
          .then(response => {
            console.log('获取合同详情成功:', response.data)
            contract.value = response.data.contract
            milestoneStatus.value = response.data.milestoneStatus
            depositDescription.value = response.data.depositDescription || ''
            executionDescription.value = response.data.executionDescription || ''
          })
          .catch((err) => {
            console.error('获取合同详情失败', err)

            if (err.response) {
              // 服务器返回错误状态码
              switch (err.response.status) {
                case 400:
                  errorMessage.value = `请求参数错误: ${err.response.data?.message || '无效的合同ID'}`
                  break
                case 401:
                  errorMessage.value = '未授权，请重新登录'
                  // 跳转到登录页
                  setTimeout(() => {
                    router.push('/login')
                  }, 2000)
                  break
                case 403:
                  errorMessage.value = '权限不足，无法查看该合同'
                  break
                case 404:
                  errorMessage.value = '合同不存在或已被删除'
                  break
                case 500:
                  errorMessage.value = '服务器内部错误，请稍后再试'
                  break
                default:
                  errorMessage.value = `请求失败 (${err.response.status}): ${err.response.statusText}`
              }
            } else if (err.request) {
              // 请求已发送，但没有收到响应
              errorMessage.value = '无法连接到服务器，请检查网络连接'
            } else {
              // 请求设置时出错
              errorMessage.value = `请求错误: ${err.message}`
            }
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 获取条款
    const fetchClauses = () => {
      if (!contractId.value) {
        console.log('合同ID不存在，无法获取条款')
        return
      }

      axios.get(`/auth/clauses/contract/${contractId.value}`)
          .then(response => {
            clauses.value = response.data
          })
          .catch((err) => {
            console.error('获取合同条款失败', err)
            errorMessage.value = '获取合同条款失败，请重试'
          })
    }

    // 开始履行合同
    const startContractExecution = () => {
      loading.value = true
      operationSuccess.value = false

      axios.put(`/auth/contracts/${contractId.value}/start-execution`)
          .then(() => {
            operationSuccess.value = true
            operationMessage.value = '已开始履行合同，进度更新为定金阶段'
            fetchContractDetails()
          })
          .catch(error => {
            console.error('开始履行合同失败', error)
            errorMessage.value = error.response?.data?.message || '开始履行合同失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 更新定金阶段描述
    const updateDepositDescription = () => {
      loading.value = true
      operationSuccess.value = false

      axios.put(`/auth/contracts/${contractId.value}/update-deposit`, {
        description: depositModalContent.value
      })
          .then(() => {
            depositModalVisible.value = false
            operationSuccess.value = true
            operationMessage.value = '定金阶段描述已更新'
            fetchContractDetails()
          })
          .catch(error => {
            console.error('更新定金阶段描述失败', error)
            errorMessage.value = error.response?.data?.message || '更新定金阶段描述失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 打开定金阶段模态框
    const openDepositModal = () => {
      depositModalContent.value = depositDescription.value
      depositModalVisible.value = true
    }

    // 更新执行阶段描述
    const updateExecutionDescription = () => {
      loading.value = true
      operationSuccess.value = false

      axios.put(`/auth/contracts/${contractId.value}/update-execution`, {
        description: executionModalContent.value
      })
          .then(() => {
            executionModalVisible.value = false
            operationSuccess.value = true
            operationMessage.value = '执行阶段描述已更新'
            fetchContractDetails()
          })
          .catch(error => {
            console.error('更新执行阶段描述失败', error)
            errorMessage.value = error.response?.data?.message || '更新执行阶段描述失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 打开执行阶段模态框
    const openExecutionModal = () => {
      executionModalContent.value = executionDescription.value
      executionModalVisible.value = true
    }

    // 确认归档合同
    const confirmArchiving = () => {
      loading.value = true
      operationSuccess.value = false

      axios.put(`/auth/contracts/${contractId.value}/archive`)
          .then(() => {
            operationSuccess.value = true
            operationMessage.value = '合同已成功归档'
            setTimeout(() => {
              router.push('/employee/ongoing-contracts')
            }, 1500)
          })
          .catch(error => {
            console.error('归档合同失败', error)
            errorMessage.value = error.response?.data?.message || '归档合同失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 返回上一级
    const goBack = () => {
      router.push('/employee/ongoing-contracts')
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 获取进度条样式类
    const getProgressClass = (status) => {
      switch (status) {
        case 1: return 'bg-warning'
        case 2: return 'bg-info'
        case 3: return 'bg-primary'
        case 4: return 'bg-success'
        default: return 'bg-secondary'
      }
    }

    // 获取进度条宽度
    const getProgressWidth = (status) => {
      return status * 25 + '%'
    }

    // 获取进度文本
    const getProgressText = (status) => {
      return milestoneStatusMap[status] || `未知状态: ${status}`
    }

    // 监听路由参数变化
    watch(() => route.params.contractId, (newId) => {
      if (newId && newId !== contractId.value) {
        console.log('路由参数变化，新ID:', newId)
        fetchContractDetails()
      }
    })

    onMounted(() => {
      console.log('组件挂载，初始路由参数:', route.params)
      fetchContractDetails()
      fetchClauses()
    })

    return {
      contractId,
      contract,
      clauses,
      milestoneStatus,
      depositDescription,
      executionDescription,
      loading,
      errorMessage,
      operationSuccess,
      operationMessage,
      depositModalVisible,
      executionModalVisible,
      depositModalContent,
      executionModalContent,
      goBack,
      formatDate,
      getProgressClass,
      getProgressWidth,
      getProgressText,
      startContractExecution,
      openDepositModal,
      updateDepositDescription,
      openExecutionModal,
      updateExecutionDescription,
      confirmArchiving
    }
  }
}
</script>

<style scoped>
.header {
  background-color: #f8f9fa;
  padding: 15px;
  border-bottom: 1px solid #dee2e6;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  padding: 15px;
  color: #721c24;
  background-color: #f8d7da;
  border-radius: 4px;
  margin: 15px 0;
}

.contract-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-top: 20px;
}

.progress-section {
  margin-top: 30px;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  position: relative;
}

.progress-line {
  position: absolute;
  top: 15px;
  left: 30px;
  right: 30px;
  height: 2px;
  background-color: #e9ecef;
  z-index: 0;
}

.progress-line.active {
  background-color: #007bff;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1;
}

.step-indicator {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 5px;
}

.step.active .step-indicator {
  background-color: #007bff;
  color: white;
}

.clauses-section {
  margin-top: 30px;
}

.action-area {
  margin-bottom: 50px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-dialog {
  max-width: 500px;
  width: 100%;
}

.modal-content {
  background-color: white;
  border-radius: 4px;
}

.modal-header {
  padding: 15px;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  padding: 15px;
}

.modal-footer {
  padding: 15px;
  border-top: 1px solid #dee2e6;
  display: flex;
  justify-content: flex-end;
}

/* 新增样式 */
.bg-gradient-primary {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
}

.bg-gradient-info {
  background: linear-gradient(135deg, #06b6d4, #0891b2);
}

.bg-gradient-success {
  background: linear-gradient(135deg, #10b981, #059669);
}

/* 按钮样式 */
.btn {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  border: none;
  border-radius: 0.5rem;
  padding: 0.75rem 1.5rem;
  font-weight: 500;
}

.btn:hover {
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
}

.btn:active {
  transform: translateY(1px);
  box-shadow: 0 5px 10px -3px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(
      to right,
      rgba(255, 255, 255, 0) 0%,
      rgba(255, 255, 255, 0.3) 50%,
      rgba(255, 255, 255, 0) 100%
  );
  transform: rotate(30deg);
  transition: all 0.6s ease;
}

.btn:hover::after {
  left: 120%;
}

.btn-lg {
  padding: 0.875rem 1.75rem;
  font-size: 1.125rem;
}

.btn i {
  vertical-align: middle;
}

.modal-footer .btn {
  margin-left: 0.5rem;
}

.lift {
  transform: translateY(0);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.lift:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
}

/* 操作成功提示样式优化 */
.success-notification {
  display: flex;
  align-items: flex-start;
  background: linear-gradient(135deg, #f0fdf4, #dcfce7);
  border: 1px solid #bbf7d0;
  border-radius: 0.75rem;
  padding: 1.25rem;
  animation: fadeIn 0.5s ease-out, slideUp 0.3s ease-out, fadeOut 0.5s ease-in 3s forwards;
  overflow: hidden;
  position: relative;
}

.success-notification::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background-color: #10b981;
}

.notification-icon {
  flex-shrink: 0;
  margin-right: 1rem;
  margin-top: 0.25rem;
}

.notification-icon i {
  color: #10b981;
  font-size: 2rem;
  background-color: rgba(16, 185, 129, 0.1);
  border-radius: 50%;
  width: 2.5rem;
  height: 2.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-content {
  flex-grow: 1;
}

.notification-title {
  color: #059669;
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.notification-message {
  color: #15803d;
  margin: 0;
  font-size: 0.95rem;
  line-height: 1.5;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(20px); }
  to { transform: translateY(0); }
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; visibility: hidden; }
}

.form-floating {
  position: relative;
}

.form-floating label {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  padding: 0.75rem 0.75rem;
  pointer-events: none;
  border: 1px solid transparent;
  transform-origin: 0 0;
  transition: opacity 0.1s ease-in-out, transform 0.1s ease-in-out;
}

.form-floating .form-control {
  padding: 1.25rem 0.75rem;
}

.form-floating .form-control:not(:-moz-placeholder-shown) {
  padding-top: 1.625rem;
  padding-bottom: 0.625rem;
}

.form-floating .form-control:not(:placeholder-shown) {
  padding-top: 1.625rem;
  padding-bottom: 0.625rem;
}

.form-floating .form-control:not(:-moz-placeholder-shown) ~ label {
  opacity: 0.65;
  transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
}

.form-floating .form-control:not(:placeholder-shown) ~ label {
  opacity: 0.65;
  transform: scale(0.85) translateY(-0.5rem) translateX(0.15rem);
}

/* 文本框样式 */
.textarea-large {
  min-height: 180px;
  width: 100%;
  border-radius: 0.75rem;
  font-size: 1rem;
  transition: all 0.2s ease;
}

.textarea-large:focus {
  box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25);
  border-color: #3b82f6;
}

/* 模态框尺寸调整 */
.modal-xl {
  max-width: 1140px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .textarea-large {
    min-height: 140px;
  }

  .modal-xl {
    max-width: 90%;
  }

  .contract-info {
    grid-template-columns: 1fr;
  }

  .btn {
    padding: 0.625rem 1.25rem;
    font-size: 0.9375rem;
  }

  .btn-lg {
    padding: 0.75rem 1.5rem;
    font-size: 1rem;
  }

  .success-notification {
    padding: 1rem;
  }

  .notification-icon i {
    font-size: 1.5rem;
    width: 2rem;
    height: 2rem;
  }
}
</style>
